//import Qs from "qs";
import util from "./common/js/util.js";
import 'dingtalk-jsapi/entry/mobile';
const updateManager = dd.getUpdateManager()
var $urls="";
var $url="";

App({
  //全局变量设置
  prototype: {
    $Token: "",
    $SysPhone: "",
    $userName: "",
    $userId: "",
    $url: "",
    $urls: "",
    $indexObj: "",
    $dev: "",// pro 正式 dev开发
    $corpId: "ding2e2011827f67ec7d35c2f4657eb6378f", //恒丽 正式 corpId
    $corpId_dev: "",//
    $corpId_test: "ding387df0d1eac4a910ffe93478753d9884",//lqf 测试
    $appId_hl_neibu: "5000000006010649",//appid 恒丽 企业内部appid
    $appId_test_neibu: "5000000005157291",//appid 岳鸿test 企业内部appid
    unionId: "",
    error_num: 0, //网络请求错误次数 大于6次提示
    error_count: 0,//错误提示错误次数
    navigateBack: {},
    unSubmitArr:[]
  },
  $post(url, params,type) {
    // 
    let storage = null;
    try {
      storage = dd.getStorageSync({ key: "userMessage" }).data;
    } catch (error) {
    }
    // 

    let Token = storage ? storage.token : "";
    if(params){
      params.Authorization=Token;
    }else{
      params={
        Authorization:Token
      }
    }
  
    let that = this;
    return new Promise((reslove, reject) => {
      // header: {"Content-type": "application/x-www-form-urlencoded"},
      // header: { "Content-type": "application/json;charset=UTF-8" },

      let allUrl=$urls + url;
    //  console.log("--allUrl:"+allUrl);
    //  console.log("--Token:",Token);
    let content_type="application/x-www-form-urlencoded";
    
    if(type){
      content_type="application/json;charset=UTF-8";
    }
    
      dd.httpRequest({
        url: allUrl,
        header: { 
          "Content-type": content_type,
          "Authorization":  Token,//Authorization这种设置无效
         },
        data: params,
        method: "POST",
        // dataType:"text",
        success: (res) => {
          //console.log(res);

          // dd.hideLoading();
          
          try {
            
            if (res.data.code == 200) {
              reslove(res);
            }else if (res.data.code == 401) {
              // dd.hideLoading();
              if (url != "/user/userLogin/login"&&this.prototype.error_num ==0) {
              //   this.authLoginFn();
              }
              reslove(res);
            }else if (res.data.code == 500) {
              // dd.showToast({
              //   title: res.data.message,
              //   duration: 2000
              // });
               dd.alert({
                content: res.data.message
             })
              
              reslove(res);
            }else {

              reject(res);
            };

          }
          catch (error) {
            console.log("---catch error");

            this.authLoginFn()
          }
          this.prototype.error_num = 0;
          this.prototype.error_count = 0;
        },
        fail: err => {
          console.log("--fail-url:", url);
          console.log("---fail err", err);

          // util.message("网络似乎出现了问题")
          if (url != "/user/userLogin/login") {
            //  this.authLoginFn();

          }

          dd.hideLoading();

          //首页待办token异常

          // err.error 13 超时
          if (this.prototype.error_num == 0 && err.error == 13) {
            this.prototype.error_num++;
            dd.confirm({
              title: '温馨提示',
              content: '网络似乎出现了问题,请您在页面下拉刷新重试?',
              confirmButtonText: '知道了',
              cancelButtonText: '关闭',
              success: (result) => {
                if (result.confirm) {
                  this.prototype.error_num = 0;
                  // that.authLoginFn();
                }
              },
            });
          } else if (this.prototype.error_num == 0 && err.error == 14) {
            //token异常 被重定向到首页了
            that.authLoginFn();
            that.prototype.error_num++;
          } else {
            return reject(err);
          }

        }
      });
    }).then(res => {
      return res.data;
    }).catch(err => {
      dd.hideLoading();

      try {
       console.log("---err ss:",err);
       util.message(err.errorMessage)
        
      } catch (error) {
        console.log("--error:", error);
      }
      // util.message(JSON.stringify(err));

      // if (util.isNull(this.$Token)) uni.reLaunch({url: "/pages/Home/Home.vue"});


    })
  },
  isAuthLoginUrl(url) {
    let isAutoLogin = true;
     if (url != "/user/userLogin/login") {
      isAutoLogin = false;
    }
    return isAutoLogin;
  },
  $postFile(url,params) {
    let storage = null;
    try {
      storage = dd.getStorageSync({ key: "userMessage" }).data;
    } catch (error) {
    }
    // 

    let Token = storage ? storage.token : "";
    if(params){
      params.Authorization=Token;
    }else{
      params={
        Authorization:Token
      }
    }
    // console.log("---FileUpload:", params);
    return new Promise((reslove, reject) => {
     
      dd.uploadFile({
        url: $urls + url,
        fileType: 'image',
        fileName: 'file',
        filePath: params.url,
        formData: params,
        success: (res) => {
          // console.log("--返回数据:",res);
          try {
            if(res.success){
              reslove(res.data);
            }else{
              reslove({code:500})
            }
            
          } catch (error) {
            reject(res)
            console.log(error);
          }

        },
        fail: function (err) {
          dd.hideLoading()
          util.message("文件上传失败!");

          console.log(err);
          reject(err)
        },
      });
    })
  },
  getIsLogin(){
    let that = this;
    let api = "/user/info/getIsLogin", list = {  };
    this.$post(api, list).then(re => {
      try {
        if (re.code == 401) {
          that.authLoginFn().then(res=>{
           // console.log("--res:",res);
          })
        }
        else {
        };
      } catch (error) {
        
      }

    }).catch(err => {
      
      
    });
  },
  authLoginFn() {
    let that = this;

    // console.log(`dd.corpId:${dd.corpId}`);
    // dd.showLoading({
    //   content: '自动登录中...',
    // })
    return new Promise((reslove, reject) => {
      dd.getAuthCode({
        success: function (res) {
          console.log("--authCode::",res);
          let unionId = res.authCode;
          that.$post("/user/userLogin/login", { code: unionId }).then(re => {
          
            try {
              if (re.code == 200) {               
                dd.setStorageSync({ key: "userMessage", data: re.data });
                         
                that.prototype.$Token = re.data.token;
                that.prototype.$userId = re.data.userId;
                that.prototype.$userName = re.data.userName;
                dd.hideLoading();

                reslove(re.data);
              }
              else {
                dd.hideLoading();
                that.prototype.error_num++;
                reject(re)
              }
            } catch (error) {

            }
  
          }).catch(err => {

            dd.hideLoading();

          });
        },
        fail: function (err) {
          // console.log(err);
          util.message("获取授权信息code失败,请自行手动登录:err"+err);
          dd.hideLoading();
          if (that.prototype.error_num == 0) {
            that.prototype.error_num++;
  
            dd.confirm({
              title: '网络错误',
              content: '' + JSON.stringify(err),
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              success: function (res) {
                if (res.confirm) {
                  that.prototype.error_num = 0;
                  //  dd.redirectTo({ url: "/pages/login/login" });
                }
              }
            })
            try {
              this.prototype.error_num++;
            } catch (error) {
              console.log(error);
            }
          }
  

        }
      });
    }).then(res => {
         return res.data;
   }).catch(err => {
         try {
          console.log("---err ss:",err);
          util.message(err.errorMessage)
         } catch (error) {
           console.log("--error:", error);
         }
   })


  },
  fileView(url) {
    if (url.indexOf("https") == -1) {
      url = url.replace("http", "https")
    }
    //    console.log("fileView:",url);
    dd.previewImage({
      current: 1,
      urls: [
        url
      ],
    });
  },
  fileViews(urls, current) {
    urls.forEach(url => {
      if (url.indexOf("https") == -1) {
        url = url.replace("http", "https")
      }
    })
    let index = 0;
    if (current) {
      index = current
    }
    dd.previewImage({
      current: index,
      urls,
    });
  },
  onLaunch(options) {
    dd.getSystemInfo({
      success: (res) => {
        console.log(res);
        this.prototype.windowHeight = res.windowHeight;
        this.prototype.windowWidth = res.windowWidth;
        this.prototype.platform = res.platform;
      }
    })

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // // res.hasUpdate是否有更新
      //util.message(res.hasUpdate+"")
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function (ret) {
          //console.log(ret.version) // 更新版本号
          dd.confirm({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })

    console.log(dd.corpId);
    console.info('App onLaunch');
    const appIdRes = dd.getAppIdSync();
    console.log(" appid:",appIdRes.appId);

    console.log("$corpId:", this.prototype.$corpId);
    /**
     * $urls 图片资源访问路径
     * $url 接口请求访问路径
     */
    if (util.isNotEmpty(dd.corpId)) {
      
       if (dd.corpId == this.prototype.$corpId_test) {
        $urls = "http://220.161.77.66:10111/hl";
        $url = "http://220.161.77.66:10111";
 
        this.prototype.$dev = "dev";

        console.log("开发环境: lqf 测试");
      }
      else if (dd.corpId == this.prototype.$corpId) {
     
        if (appIdRes.appId == this.prototype.$appId_hl_neibu) {
          //恒丽 企业内部
          // $urls = "http://www.liuqingfeng.top/hl";
          // $url = "http://www.liuqingfeng.top";
          $urls = "http://220.161.77.66:10111/hl";
          $url = "http://220.161.77.66:10111";
          this.prototype.$dev = "pro";
          console.log("生产环境: 恒丽");

        } 
      }
      
    } else {
      let dev = "test"
      $urls = `http://www.liuqingfeng.top/hl`;
      $url = `http://www.liuqingfeng.top`;
    }
    //图片资料访问域名 因为现在是绝对路径了，所以不需要拼接访问路径 2022-05-06


    let storage = null;
    try {
      storage = dd.getStorageSync({ key: "userMessage" }).data;
    } catch (error) {
    }
    // 
    let $Token = storage ? storage.token : "";
    if (util.isNotEmpty(storage)) {
      this.prototype.$Token = $Token;
      // this.prototype.$SysPhone = storage.SysPhone;
      this.prototype.$userName = storage.userName;
      this.prototype.$userId = storage.userId;
    };

    // this.authLoginFn();

    
    if (!dd.isIDE) {
      this.authLoginFn();
    // this.getIsLogin();

     
    } else {
      if (util.isNotEmpty(storage)) {

      } else {

      //  this.authLoginFn();
      }
    }
  },

  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  }
});
